// components/portfolio/portfolio.js
const cred = require("../../utils/credentials");
const db = require('../../utils/db');
const datetime = require('../../utils/datetime');

Component({
  properties: {
    limit: {
      type: Number,
      value: 20
    },
    allowLoadMore: {
      type: Boolean,
      value: true
    },
    allowInactiveRecords: {
      type: Boolean,
      value: false
    }
  },

  data: {
    busy: {
      type: Boolean,
      value: false
    },
    openId: {
      type: String,
      value: ""
    },
    borrowing: {
      type: Array,
      value: []
    },
    skip: {
      type: Number,
      value: 0
    },
    exhausted: {
      type: Boolean,
      value: false
    }
  },

  methods: {
    doLogin: async function () {
      this.setData({
        busy: true,
        skip: Date.now(),
        exhauseted: false
      });
      
      await cred.getUserInfo();
      const id = await cred.getOpenId();
      
      this.setData({
        busy: false,
        openId: id,
        borrowing: []
      });

      await this.grabMoreData();
    },

    grabMoreData: async function () {
      this.setData({
        busy: true
      });

      const queryFn = this.data.allowInactiveRecords ? db.getRecords.bind(db) : db.getActiveRecords.bind(db);

      const entries = await queryFn(this.data.limit, this.data.skip);

      console.log(entries);

      let newSkipValue = this.data.skip;

      entries.map(it => {
        if (newSkipValue > it['borrowTime']) {
          newSkipValue = it['borrowTime'];
        }
        it['expired'] = it.isOpen && Date.now() > it['expectedReturnTime'];
        it['borrowTime'] = datetime.toFriendlyTime(it['borrowTime']);
        it['expectedReturnTime'] = datetime.toFriendlyTime(it['expectedReturnTime']);
        if (!it.isOpen) {
          it['returnTime'] = datetime.toFriendlyTime(it['returnTime']);
        }
        return it;
      });

      this.setData({
        busy: false,
        borrowing: this.data.borrowing.concat(entries),
        skip: newSkipValue - 1,
        exhausted: entries.length < this.data.limit
      });
    }
  },

  
  lifetimes: {
    attached: function () {
      this.setData({
        busy: false,
        openId: '',
        borrowing: []
      });
      if (cred.isAuthorized()) {
        this.doLogin();
      }
    }
  },

  pageLifetimes: {
    show: function () {
      if (cred.isAuthorized() && !this.data.busy) {
        this.doLogin();
      }
    }
  }
})
